<?php
/**
 * Ajax请求
 */
namespace Member\Controller;
use Org\Yike\Category;
use Org\Yike\Member;
class AjaxController extends CommonController {
    public function _initialize(){
        parent::_initialize();
        $this->is_login();
    }

    public function getEstate(){
        $area_id = intval($_POST['area_id']);
        if(!$area_id){
            die(json_encode(array('status'=>0,'msg'=>'参数错误')));
        }
        $cate_list = M('area_cate')->where(array('status'=>1))->select();
        $cate = new Category();
        $ids = $cate::getChiIds($cate_list,$area_id,1);
        array_push($ids,$area_id);
        $list = M('estate')->where(array('status'=>1,'area_id'=>array('in',$ids)))->field('id,title')->order('id desc')->select();
        if($list){
            die(json_encode(array('status'=>1,'data'=>$list,'msg'=>'获取小区成功')));
        }else{
            die(json_encode(array('status'=>0,'msg'=>'获取小区失败')));
        }
    }
    public function getDict ()
    {
        $eid = intval($_POST['eid']);
        if (!$eid) {
            die(json_encode(array('status' => 0, 'msg' => '参数错误')));
        }
        $list = M ('dict')->where (array ('estate_id'=>$eid))->select ();
        if($list){
        die(json_encode(array('status'=>1,'data'=>$list,'msg'=>'获取字典成功')));
        }else{
            die(json_encode(array('status'=>0,'msg'=>'获取字典失败')));
        }
    }
    //查看业主信息
    public function view (){
        $used_id = I ('post.used_id', '');
        $field = I ('post.field', '');
        $mod = M ('user');
        $user_id = session('userInfo.id');
        $info = M ('used')->field ('phone,phone1,phone2,phone3')->where (array ('id'=>$used_id))->find();
        foreach ($info as $k=>$v){
            if (empty ($v)) unset ($info[$k]);
        }
        $phones = '';
        if (!empty ($info['phone'])) $phones .= $info['phone'].',';
        if (!empty ($info['phone1'])) $phones .= $info['phone1'].',';
        if (!empty ($info['phone2'])) $phones .= $info['phone2'].',';
        if (!empty ($info['phone3'])) $phones .= $info['phone3'].',';
        //检查经纪人查看业主信息的今天次数
        $userInfo = $mod->field ('view_time,view_freq')->where ('id='.$user_id)->find ();
        $today = date ('Y-m-d');
        $view_phone_count = M ('configure')->where ('id='.C ('VIEW_PHONE_COUNT'))->getField('val');
        if ($today.' 00:00:00' != $userInfo['view_time']){
            $mod->where (array ('id'=>$user_id))->setField (array ('view_time'=>$today,'view_freq'=>1));
        }elseif($userInfo['view_freq'] < $view_phone_count){
            $mod->where (array ('id'=>$user_id))->setInc ('view_freq');
        }else{
            exit (json_encode(array ('state'=>2,'text'=>'你当天查看次数已用完')));
        }

        //检查经纪人有没有跟进房源
        $starTime = strtotime ($today." 00:00:00");
        $endTime = strtotime ($today." 23:59:59");
        $f_mod = M ('follow');
        $follow = $f_mod
            ->where (array ('user_id'=>$user_id,'status'=>-1))
            ->find ();
        if (empty ($follow)){
            $follow_data = array (
                'user_id' => $user_id,
                'source_id' => $used_id,
                'uname' => session('userInfo.username'),
                'discuss' => '申请了查看业主联系电话',
                'type' => 3,
                'status' => -1,
                'add_time' => time ()
            );
            $f_mod->add ($follow_data);
        }else{
            exit (json_encode(array ('state'=>3,'text'=>'跟进','data'=>array ('used'=>$follow['source_id'],'user_id'=>$user_id))));
        }

        if (! empty($info)){
            $follow = M ('follow')->where ('type=3 and status<>-1 and source_id='.$used_id)->select ();
            foreach ($follow as &$v){
                $v['add_time'] = date ('Y-m-d H:i:s',$v['add_time']);
            }
            exit (json_encode(array ('state'=>1,'text'=>trim ($phones, ','),'data'=>$info,'follow'=>$follow)));
        }
        exit (json_encode(array ('state'=>0,'text'=>'')));
    }

    public function addFollow ()
    {
        $data[user_id] = intval($_POST['user_id']);
        $data[source_id] = intval($_POST['source_id']);
        $data[type] = intval($_POST['type']);
        $data[discuss] = $_POST['discuss'];
        $data[add_time] = date("Y-m-d H:i:s");

        if($result = M('follow')->add($data)){
            die(json_encode(array('id'=>$result,'status'=>1,'msg'=>'添加跟进信息成功')));
        }else{
            die(json_encode(array('status'=>0,'msg'=>'添加跟进信息失败')));
        }

    }

    public function editFollow ()
    {
       // $data[user_id] = intval($_POST['user_id']);
       // $data[source_id] = intval($_POST['source_id']);
       // $data[type] = intval($_POST['type']);
        $data[id] = $_POST['id'];
        $data[discuss] = $_POST['discuss'];
        //$data[add_time] = date("Y-m-d H:i:s");
        //if (!$data[discuss]) {
        //    die(json_encode(array('status' => 0, 'msg' => '参数错误')));
        //}
        if($result = M('follow')->where(array('id'=>$data[id]))->save($data)){
            die(json_encode(array('id'=>$result,'status'=>1,'msg'=>'添加跟进信息成功')));
        }else{
            die(json_encode(array('status'=>0,'msg'=>'添加跟进信息失败')));
        }

    }
    //获取区域
    public function getArea (){
        $areaid = I ('post.areaid', '');
        $areas =  M ('area_cate')->where ('pid='.$areaid)->select ();
        if ($areas){
            exit (json_encode (array ('state'=>'ok','data'=>$areas)));
        }else{
            exit (json_encode (array ('state'=>'fail','data'=>'')));
        }
    }
    //获取小区详情
    public function getEstates (){
        $eid = I ('post.eid', '');
        $mod = M ('estate');
        $mod->field ('build,unit,floor,room');
        $mod->where (array ('id'=>$eid));
        $data = $mod->find ();
        if($data){
            die(json_encode(array('state'=>'ok','data'=>$data,'msg'=>'获取小区成功')));
        }else{
            die(json_encode(array('state'=>0,'msg'=>'获取小区失败')));
        }
    }
    //获取小区是否存在
    public function getIsEstate (){
        $title = I ('post.title', '');
        $mod = M ('estate');
        $mod->field ('id,title');
        $mod->where (array ('title'=>$title));
        $data = $mod->find ();
        if($data){
            die(json_encode(array('state'=>'ok','data'=>$data,'msg'=>'获取小区成功')));
        }else{
            die(json_encode(array('state'=>0,'msg'=>'获取小区失败')));
        }
    }
    //获取店铺
    public function getShop (){
        $shop = I ('post.shop', '');
        $map['title'] = array ('like','%'.$shop.'%');
        $map['status'] = 1;
        $data = M ('shop')->where ($map)->select ();
        if($data){
            die(json_encode(array('state'=>'ok','data'=>$data,'msg'=>'获取成功')));
        }else{
            die(json_encode(array('state'=>0,'msg'=>'获取失败')));
        }
    }
    ////获取分组
    public function getDivision (){
        $shop_id = I ('post.shop_id', '');
        $data = M ('division')->where ('shop_id='.$shop_id)->select ();
        if($data){
            die(json_encode(array('state'=>'ok','data'=>$data,'msg'=>'获取成功')));
        }else{
            die(json_encode(array('state'=>0,'msg'=>'获取失败')));
        }
    }
    //审核房源
    public function examine (){
        $id = I ('post.id', '');
        $sig = I ('post.sig','');
        if ($sig == 'pass'){
            $data = M ('used')->where('id='.$id)->setField('status', 3);
        }
        if ($sig == 'nopass'){
            $data = M ('used')->where('id='.$id)->setField('status', 0);
        }
        if($data){
            die(json_encode(array('state'=>'ok','data'=>$data,'msg'=>'审核成功')));
        }else{
            die(json_encode(array('state'=>0,'msg'=>'审核失败')));
        }
    }
    //根据区域获取店铺
    public function getShopForarea (){
        $area_id = I ('post.area_id', '');
        $map['status'] = 1;
        $map['area_id'] = $area_id;
        $data = M ('shop')->where ($map)->select ();
        if($data){
            die(json_encode(array('state'=>'ok','data'=>$data,'msg'=>'获取成功')));
        }else{
            die(json_encode(array('state'=>0,'msg'=>'获取失败')));
        }
    }
    //设置字典值
    public function setDict (){
        $table = I ('post.table', '');
        $val = I ('post.val', '');
        $id = I ('post.id', '');
        $floor = I ('post.floor');
        $usedid = I ('post.usedid');
        $type = I ('post.type');
        switch ($table){
            case 'build':
                $name = 'bid';
                //别名不能重复
                if ($type == 'alias'){
                    $eid = M ($table)->where ('bid='.$id)->getField('estate_id');
                    $alias = M ($table)->where (array ('alias'=>$val,'estate_id'=>$eid))->find();
                    if (!empty ($alias)){
                        die (json_encode(array('state'=>0,'data'=>'','msg'=>'别名不能重复')));
                    }
                }
                $msg = '修改了楼栋别名';
                break;
            case 'unit':
                $name = 'unid';
                //别名不能重复
                if ($type == 'alias'){
                    $bid = M ($table)->where ('unid='.$id)->getField('build');
                    $alias = M ($table)->where (array ('alias'=>$val,'build'=>$bid))->find();
                    if (!empty ($alias)){
                        die (json_encode(array('state'=>0,'data'=>'','msg'=>'别名不能重复')));
                    }
                }
                $msg = '修改了单元别名';
                break;
            case 'room':
                $name = 'rid';
                //别名不能重复
                if ($type == 'alias'){
                    $unid = M ($table)->where ('rid='.$id)->getField('unit');
                    $alias = M ($table)->where (array ('alias'=>$val,'unit'=>$unid))->find();
                    if (!empty ($alias)){
                        die (json_encode(array('state'=>0,'data'=>'','msg'=>'别名不能重复')));
                    }
                }
                $model =  M ('room');
                break;
            default :
                $name = '';
                break;
        }
        $data = M ($table)->where ($name.'='.$id)->setField($type, $val);
        if ($table == 'room'){
            //修改房源别名时，同一单元下房号全部修改
            $room = $model->field ('unit,room,floor')->where(array ('rid'=>$id))->find();
            switch ($type){
                case 'alias':
                    $model->where ('unit='.$room['unit'].' and room="'.$room['room'].'"')->save (array ('alias'=>$val));
                    $msg = '修改了房间别名';
                    break;
                case 'area':
                    $model->where ('unit='.$room['unit'].' and room="'.$room['room'].'"')->save (array ('area'=>$val));
                    $msg = '修改了房间面积';
                    break;
                case 'aspect':
                    $model->where ('unit='.$room['unit'].' and room="'.$room['room'].'"')->save (array ('aspect'=>$val));
                    $msg = '修改了朝向';
                    break;
                case 'chamber':
                    $model->where ('unit='.$room['unit'].' and room="'.$room['room'].'"')->save (array ('chamber'=>$val));
                    break;
                case 'hall':
                    $model->where ('unit='.$room['unit'].' and room="'.$room['room'].'"')->save (array ('hall'=>$val));
                    break;
                case 'kitchen':
                    $model->where ('unit='.$room['unit'].' and room="'.$room['room'].'"')->save (array ('kitchen'=>$val));
                    break;
                case 'toilet':
                    $model->where ('unit='.$room['unit'].' and room="'.$room['room'].'"')->save (array ('toilet'=>$val));
                    break;
                case 'balcony':
                    $model->where ('unit='.$room['unit'].' and room="'.$room['room'].'"')->save (array ('balcony'=>$val));
                    break;
                case 'f_alias':
                    $model->where ('unit='.$room['unit'].' and floor="'.$room['floor'].'"')->save (array ('f_alias'=>$val));
                    $msg = '修改了楼层别名';
                    break;
                default:
                    break;
            }

        }

        if($data){
            //记录是谁修改的
            if (!empty($usedid)){
                $follow = array (
                    'user_id' => $this->user['id'],
                    'source_id' => $usedid,
                    'uname' => $this->user['username'],
                    'discuss' => $msg,
                    'add_time' => time ()
                );
                $res = M ('follow')->add ($follow);
            }
            $data['val'] = $val;
            die(json_encode(array('state'=>'ok','data'=>$data,'msg'=>'设置成功')));
        }else{
            die(json_encode(array('state'=>0,'msg'=>'设置失败')));
        }
    }
    //生成数据字典
    public function generator (){
        $id = I ('post.id', '');
        $data = array ();
        $estate = M ('estate')->field ('id,build,unit,floor,room,address')->where ('id='.$id)->find ();
        //查询是否已生成过
        $dict = M ('dict')->field ('id')->where ('estate_id='.$id)->count ();
        $msg = '生成失败';
        if ($dict >= ($estate['build']*$estate['unit']*$estate['floor']*$estate['room'])){
            $msg = '已经生成过';
        }else{
            $ord = ord('A')-1;
            for ($i=1; $i<=$estate['build']; $i++){
                for ($ii=1; $ii<=$estate['unit']; $ii++){
                    for ($iii=1; $iii<=$estate['floor']; $iii++){
                        for ($iiii=1; $iiii<=$estate['room']; $iiii++){
                            $room = strlen ($iiii) < 2 ? '0'.$iiii: $iiii;
                            $floor = $iii == 4 ? '3A': $iii;
                            $build = chr($ord +$i);
                            $data[] = array (
                                'estate_id' => $estate['id'],
                                'build_name' => $build,
                                'build' => $build,
                                'unit_name' => $ii,
                                'unit' => $ii,
                                'floor_name' => $floor,
                                'fool' => $floor,
                                'room_name' => $room,
                                'room' => $room,
                                'addr' => $estate['address'],
                                'total_fool' => $estate['floor'],
                                'add_time' => date ('Y-m-d')
                            );
                        }
                    }

                }
             }
            $res = M ('dict')->addAll($data);
        }

        if($res){
            die(json_encode(array('state'=>'ok','data'=>$res,'msg'=>'生成成功')));
        }else{
            die(json_encode(array('state'=>0,'msg'=>$msg)));
        }
    }
    //自动填充
    public function autoEstate (){
        $title = urldecode (I ('get.term', ''));
        $map['yk_estate.title'] = array('like', '%'.$title.'%');
        $map['_logic'] = 'OR';
        $map['yk_estate.alias'] = array('like', '%'.$title.'%');
        $map['yk_estate.short'] = array('like', '%'.$title.'%');
        $data = M ('estate')
            ->field('yk_estate.id,yk_estate.title,yk_area_cate.id as area_id,yk_area_cate.name as area')
            ->join('yk_area_cate on yk_estate.area_id = yk_area_cate.id', 'LEFT')
            ->where($map)
            ->select();
        foreach ($data as $i=>$d){
            $res[$i]['label'] = $d['title'];
            $res[$i]['value'] = $d['id'];
            $res[$i]['area'] = $d['area'];
            $res[$i]['area_id'] = $d['area_id'];

        }
        if (!empty ($res)){
            exit (json_encode ($res));
        }
        exit (json_encode(''));
    }
    public function autoGroup (){
        $title = urldecode (I ('get.term', ''));
        $map['yk_division.title'] = array('like', '%'.$title.'%');
        $data = M ('division')->where($map)->select();
        foreach ($data as $i=>$d){
            $res[$i]['label'] = $d['title'];
            $res[$i]['value'] = $d['id'];
        }
        if (!empty ($res)){
            exit (json_encode ($res));
        }
        $data[] = array (
            'label' => '未知分组',
            'value' => '0'
        );
        exit (json_encode($data));
    }

    //获取楼栋
    public function getBuild (){
        $eid = I ('post.eid', '');
        $data = M ('build')->field ('bid,build,alias,height')->where (array ('estate_id'=>$eid,'status'=>1))->select ();
        if($data){
            die(json_encode(array('state'=>'ok','data'=>$data,'msg'=>'获取成功')));
        }else{
            die(json_encode(array('state'=>0,'msg'=>'获取失败')));
        }
    }
    //获取单元
    public function getUnit (){
        $bid = I ('post.id');
        $units = M ('unit')->where ("build={$bid}")->select ();
        $count = count ($units);
        if($units){
            die(json_encode(array('state'=>'ok','data'=>$units,'msg'=>'获取成功','count'=>$count)));
        }else{
            die(json_encode(array('state'=>0,'msg'=>'获取失败')));
        }
    }
    //获取房间
    public function getRoom (){
        $unid = I ('post.id');
        $rooms = M ('room')->where ("unit={$unid}")->select ();
        if($rooms){
            die(json_encode(array('state'=>'ok','data'=>$rooms,'msg'=>'获取成功')));
        }else{
            die(json_encode(array('state'=>0,'msg'=>'获取失败')));
        }
    }
    //ajax上传文件
    public function Ajaxupload(){
        $rid = $_POST['rid'];
        $data = array ();
        $data = $this->_insertPic($data);
        if (empty ($data)){
            die(json_encode(array('state'=>'-1','msg'=>'上传失败')));
        }else{
            $model =  M ('room');
            $room = $model->field ('unit,room')->where(array ('rid'=>$rid))->find();
            $res = $model->where ('unit='.$room['unit'].' and room="'.$room['room'].'"')->save (array ('img'=>$data['img']));
            if ($res){
                die(json_encode(array('state'=>'0','data'=>$data,'msg'=>'上传成功')));
            }else{
                die(json_encode(array('state'=>'-2','data'=>$data,'msg'=>'保存数据失败')));
            }
        }

    }
    //根据手机号查找房源
    public function getPhone(){
        $phone = I ('post.phone', '');
        $map['phone'] = array ('like', '%'.$phone.'%');
        $map['_logic'] = 'or';
        $map['phone1'] = array ('like', '%'.$phone.'%');
        $map['phone2'] = array ('like', '%'.$phone.'%');
        $map['phone3'] = array ('like', '%'.$phone.'%');
        $useds = M ('used')->field ('yk_used.id,yk_used.title,b.alias as balias,u.alias as ualias,r.alias')
            ->join ('yk_room r on yk_used.dict_id=r.rid', 'LEFT')
            ->join ('yk_build b on r.build=b.bid', 'LEFT')
            ->join ('yk_unit u on r.unit=u.unid', 'LEFT')
            ->where ($map)->select ();
        if ($useds){
            die(json_encode(array('state'=>'ok','data'=>$useds,'msg'=>'获取成功')));
        }else{
            die(json_encode(array('state'=>'0','data'=>$useds,'msg'=>'获取失败')));
        }
    }
    //配置设置
    public function setConfig(){
        $confID = I ('post.id');
        $confVal = I ('post.val');
        $res = M ('configure')->save (array ('id'=>$confID,'val'=>$confVal));
        if ($res){
            die(json_encode(array('state'=>'ok','data'=>$res,'msg'=>'设置成功')));
        }else{
            die(json_encode(array('state'=>'0','data'=>'','msg'=>'设置失败')));
        }
    }
    //维护人抢回
    public function setMaintain(){
        $usedid = I('post.usedid');
        $uid = I('post.uid');
        $time = I ('post.time');
        $type = I ('post.type');
        $currentDate = time ();
        $configid = C ('MAINTAIN');
        $limitTime = M ('configure')->where ('id='.$configid)->getField('val');
        $dayTime = $limitTime*86400;

        $used = M ('used')->field ('user_id,maintain,add_time,alter_time')->where ('id='.$usedid)->find();
        $addTocurrTime = $currentDate-strtotime($used['add_time']);
        if ($addTocurrTime <= $dayTime){
            die(json_encode(array('state'=>'0','data'=>'','msg'=>'录入人有更高的优先级')));
        }else {
            //查询最后一次跟进时间
            $lastTime = M ('follow')->field('add_time')
                ->where (array('source_id'=>$usedid,'type'=>$type))
                ->order ('add_time asc')
                ->find();
            $addTocurrTime = $currentDate-$lastTime;
            if ($addTocurrTime <= $dayTime){
                die(json_encode(array('state'=>'1','data'=>'','msg'=>'已有人在跟进维护')));
            }else {
                $res = M ('used')->where ('id='.$usedid)->setField('maintain', $this->user['id']);
                if ($res){
                    $userinfo = M ('user')->field ('id,username')->where ('id='.$this->user['id'])->find();
                    //写条跟进
                    $follow = array (
                        'user_id' => $this->user['id'],
                        'source_id' => $usedid,
                        'uname' => $userinfo['username'],
                        'type' =>$type,
                        'discuss' => '抢回维护人',
                        'add_time' => $currentDate
                    );
                    M ('follow')->add($follow);
                    die(json_encode(array('state'=>'ok','data'=>$userinfo,'msg'=>'抢回成功')));
                }else {
                    die(json_encode(array('state'=>'-1','data'=>'','msg'=>'网络出错')));
                }
            }

        }


    }
    public function Editphone(){
        $field = I ('post.field');
        $phone = I ('post.phone');
        $usedid = I ('post.usedid');
        $res = M ('used')->where('id='.$usedid)->setField($field,$phone);
        if ($res){
            //记录
            $data = array (
                'user_id' => $this->user['id'],
                'source_id' => $usedid,
                'type' => 3,
                'discuss' => '把业主电话修改为：'.$phone,
                'uname' => $this->user['username'],
                'add_time' => time()
            );
            M ('follow')->add ($data);
            die(json_encode(array('state'=>'ok','data'=>$res,'msg'=>'设置成功')));
        }else{
            die(json_encode(array('state'=>'0','data'=>'','msg'=>'设置失败')));
        }
    }
    public function Addphone(){
        $usedid = I ('post.usedid');
        $phone = I ('post.phone');
        $full = M ('Used')->field ('phone,phone1,phone2,phone3')->where ('id='.$usedid)->find();
        if (empty ($full['phone'])){
            $field = 'phone';
        }elseif (empty ($full['phone1'])) {
            $field = 'phone1';
        }elseif (empty ($full['phone2'])){
            $field = 'phone2';
        }elseif (empty ($full['phone3'])){
            $field = 'phone3';
        }else{
            $field = '';
        }
        $res = M ('used')->where ('id='.$usedid)->setField($field,$phone);//echo M ('used')->getLastSql();die;
        if ($res){
            //记录
            $data = array (
                'user_id' => $this->user['id'],
                'source_id' => $usedid,
                'type' => 3,
                'discuss' => '新增业主电话：'.$phone,
                'uname' => $this->user['username'],
                'add_time' => time()
            );
            M ('follow')->add ($data);
            die(json_encode(array('state'=>'ok','data'=>$res,'msg'=>'添加成功')));
        }else{
            die(json_encode(array('state'=>'0','msg'=>'最多只能添加4个号码')));
        }
    }
    public function logout (){
        session('userInfo',null);
        $name = d_name();
        setcookie('uid', '', time() - 3600, '/', $name);
        setcookie('fangcms_uid', '', time() - 3600, '/', $name);
        setcookie('fangcms_keys', '', time() - 3600, '/', $name);
        die(json_encode(array('state'=>'ok','msg'=>'退出成功')));
    }


}